<template>
  <view class="note-edit">
    <!-- Status Bar Background -->
    <view class="status-bar"></view>
    
    <!-- Top Navigation Bar -->
    <view class="nav-bar">
      <view class="nav-left">
        <u-icon name="arrow-left" size="32" @click="handleBack"></u-icon>
      </view>
      <view class="nav-right">
        <u-button 
          type="primary" 
          size="mini" 
          :plain="false"
          @click="saveNote"
        >Save</u-button>
      </view>
    </view>

    <!-- Main Content Area -->
    <scroll-view 
      scroll-y 
      class="content-container"
      :scroll-top="scrollTop"
      @scroll="handleScroll"
    >
      <!-- Title and Category Section -->
      <view class="header-section">
        <view class="title-input">
          <u-input
            v-model="note.title"
            placeholder="Note title"
            border="none"
            fontSize="36rpx"
            :customStyle="{
              padding: '20rpx 0',
              fontWeight: 'bold'
            }"
          ></u-input>
        </view>
        <view class="category-wrapper">
          <u-dropdown>
            <u-dropdown-item
              v-model="note.categoryId"
              :title="getCategoryName"
              :options="categories"
            >
              <template #title>
                <view class="category-title">
                  <u-icon name="folder" size="24" color="#666"></u-icon>
                  <text>{{ getCategoryName }}</text>
                </view>
              </template>
            </u-dropdown-item>
          </u-dropdown>
        </view>
      </view>

      <!-- Editor Toolbar -->
      <view class="editor-toolbar" :class="{ 'toolbar-shadow': isScrolled }">
        <scroll-view scroll-x class="toolbar-scroll">
          <view class="toolbar-inner">
            <view class="toolbar-group">
              <view
                v-for="(format, index) in textFormats"
                :key="index"
                class="toolbar-btn"
                :class="{ active: activeFormats.includes(format.type) }"
                @click="toggleFormat(format.type)"
              >
                <u-icon :name="format.icon" size="24"></u-icon>
              </view>
            </view>
            <view class="toolbar-divider"></view>
            <view class="toolbar-group">
              <view
                v-for="(list, index) in listFormats"
                :key="index"
                class="toolbar-btn"
                :class="{ active: activeFormats.includes(list.type) }"
                @click="toggleFormat(list.type)"
              >
                <u-icon :name="list.icon" size="24"></u-icon>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- Editor Content -->
      <view class="editor-wrapper">
        <editor
          id="editor"
          class="editor"
          :placeholder="'Start writing your note...'"
          @ready="onEditorReady"
          @input="onContentChange"
        ></editor>
      </view>

      <!-- Attachments Section -->
      <view class="attachments-section" v-if="note.attachments.length > 0">
        <view class="section-header">
          <text class="section-title">Attachments</text>
          <text class="attachment-count">{{ note.attachments.length }}</text>
        </view>
        <view class="attachments-list">
          <view 
            v-for="(file, index) in note.attachments"
            :key="index"
            class="attachment-card"
          >
            <view class="attachment-icon">
              <u-icon :name="getFileIcon(file.type)" size="32" color="#4b7bec"></u-icon>
            </view>
            <view class="attachment-info">
              <text class="attachment-name">{{ file.name }}</text>
              <text class="attachment-size" v-if="file.size">{{ formatFileSize(file.size) }}</text>
            </view>
            <view class="attachment-action">
              <u-icon 
                name="trash" 
                size="24" 
                color="#ff4d4f"
                @click="removeAttachment(index)"
              ></u-icon>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- Bottom Action Bar -->
    <view class="bottom-bar" :class="{ 'bar-shadow': !isScrolled }">
      <view class="attachment-btn" @click="showAttachmentPicker">
        <u-icon name="plus" size="24"></u-icon>
        <text>Add Attachment</text>
      </view>
    </view>

    <!-- Attachment Picker Sheet -->
    <u-action-sheet
      :show="showAttachmentSheet"
      :actions="attachmentActions"
      @close="showAttachmentSheet = false"
      @select="handleAttachmentSelect"
      :round="true"
      :cancelText="'Cancel'"
    ></u-action-sheet>
  </view>
</template>

<script>
export default {
  data() {
    return {
      noteId: null,
      editorCtx: null,
      showAttachmentSheet: false,
      activeFormats: [],
      scrollTop: 0,
      isScrolled: false,
      note: {
        title: '',
        categoryId: 1,
        content: '',
        attachments: []
      },
      categories: [
        { label: 'Anatomy', value: 1 },
        { label: 'Physiology', value: 2 },
        { label: 'Pathology', value: 3 },
        { label: 'Pharmacology', value: 4 },
        { label: 'Clinical', value: 5 }
      ],
      textFormats: [
        { type: 'bold', icon: 'bold' },
        { type: 'italic', icon: 'italic' },
        { type: 'underline', icon: 'underline' },
        { type: 'header', icon: 'font' },
        { type: 'color', icon: 'font-color' }
      ],
      listFormats: [
        { type: 'list-ul', icon: 'list' },
        { type: 'list-ol', icon: 'ordered-list' },
        { type: 'align-left', icon: 'align-left' },
        { type: 'align-center', icon: 'align-center' }
      ],
      attachmentActions: [
        { name: 'Take Photo', icon: 'camera-fill' },
        { name: 'Choose Image', icon: 'photo' },
        { name: 'Choose File', icon: 'folder' }
      ]
    }
  },
  computed: {
    getCategoryName() {
      const category = this.categories.find(c => c.value === this.note.categoryId)
      return category ? category.label : 'Select Category'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.noteId = options.id
      this.loadNoteData(options.id)
    }
    // 设置导航栏样式
    uni.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    })
  },
  methods: {
    handleBack() {
      if (this.hasUnsavedChanges()) {
        uni.showModal({
          title: 'Unsaved Changes',
          content: 'Do you want to save your changes before leaving?',
          showCancel: true,
          cancelText: 'Discard',
          confirmText: 'Save',
          success: (res) => {
            if (res.confirm) {
              this.saveNote()
            } else {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    },
    hasUnsavedChanges() {
      // 实现检查是否有未保存的更改
      return this.note.content !== '' || this.note.title !== ''
    },
    handleScroll(e) {
      this.isScrolled = e.detail.scrollTop > 0
    },
    async loadNoteData(id) {
      try {
        uni.showLoading({ title: 'Loading...' })
        // TODO: 实现从API加载笔记数据
        const note = await this.$api.notes.getById(id)
        this.note = note
        
        if (this.editorCtx) {
          this.editorCtx.setContents({ html: note.content })
        }
      } catch (error) {
        uni.showToast({
          title: 'Failed to load note',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    onEditorReady() {
      uni.createSelectorQuery()
        .select('#editor')
        .context((res) => {
          this.editorCtx = res.context
          if (this.note.content) {
            this.editorCtx.setContents({
              html: this.note.content
            })
          }
        })
        .exec()
    },
    toggleFormat(format) {
      if (!this.editorCtx) return
      
      const index = this.activeFormats.indexOf(format)
      if (index === -1) {
        this.activeFormats.push(format)
      } else {
        this.activeFormats.splice(index, 1)
      }

      this.editorCtx.format(format)
    },
    onContentChange(e) {
      this.note.content = e.detail.html
    },
    formatFileSize(size) {
      if (!size) return ''
      const units = ['B', 'KB', 'MB', 'GB']
      let index = 0
      while (size >= 1024 && index < units.length - 1) {
        size /= 1024
        index++
      }
      return `${size.toFixed(1)} ${units[index]}`
    },
    getFileIcon(type) {
      const icons = {
        image: 'image',
        pdf: 'file-text',
        doc: 'file-word',
        docx: 'file-word',
        xls: 'file-excel',
        xlsx: 'file-excel',
        ppt: 'file-powerpoint',
        pptx: 'file-powerpoint',
        txt: 'file-text',
        default: 'file'
      }
      return icons[type] || icons.default
    },
    showAttachmentPicker() {
      this.showAttachmentSheet = true
    },
    handleAttachmentSelect(index) {
      this.showAttachmentSheet = false
      
      switch(index) {
        case 0: // Take Photo
          this.takePhoto()
          break
        case 1: // Choose Image
          this.chooseImage()
          break
        case 2: // Choose File
          this.chooseFile()
          break
      }
    },
    async takePhoto() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sourceType: ['camera']
        })
        this.addAttachment({
          name: 'Photo ' + new Date().toLocaleTimeString(),
          type: 'image',
          path: res.tempFilePaths[0],
          size: res.tempFiles[0].size
        })
      } catch (error) {
        uni.showToast({
          title: 'Failed to take photo',
          icon: 'error'
        })
      }
    },
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 5,
          sourceType: ['album']
        })
        res.tempFiles.forEach((file, index) => {
          this.addAttachment({
            name: file.path.split('/').pop(),
            type: 'image',
            path: res.tempFilePaths[index],
            size: file.size
          })
        })
      } catch (error) {
        uni.showToast({
          title: 'Failed to choose images',
          icon: 'error'
        })
      }
    },
    async chooseFile() {
      // #ifdef APP-PLUS
      try {
        const res = await uni.chooseFile({
          count: 5,
          extension: ['.pdf', '.doc', '.docx', '.txt']
        })
        res.tempFiles.forEach(file => {
          this.addAttachment({
            name: file.name,
            type: this.getFileExtension(file.name),
            path: file.path,
            size: file.size
          })
        })
      } catch (error) {
        uni.showToast({
          title: 'Failed to choose files',
          icon: 'error'
        })
      }
      // #endif
      
      // #ifdef H5
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.pdf,.doc,.docx,.txt'
      input.multiple = true
      input.onchange = (event) => {
        Array.from(event.target.files).forEach(file => {
          this.addAttachment({
            name: file.name,
            type: this.getFileExtension(file.name),
            file: file,
            size: file.size
          })
        })
      }
      input.click()
      // #endif
    },
    getFileExtension(filename) {
      return filename.split('.').pop().toLowerCase()
    },
    addAttachment(file) {
      this.note.attachments.push(file)
    },
    removeAttachment(index) {
      uni.showModal({
        title: 'Remove Attachment',
        content: 'Are you sure you want to remove this attachment?',
        success: (res) => {
          if (res.confirm) {
            this.note.attachments.splice(index, 1)
          }
        }
      })
    },
    async saveNote() {
      if (!this.validateNote()) return

      try {
        uni.showLoading({ title: 'Saving...' })
        
        // 上传附件
        const uploadedAttachments = await this.uploadAttachments()
        
        // 准备保存的数据
        const noteData = {
          ...this.note,
          attachments: uploadedAttachments
        }
        
        // 调用保存API
        if (this.noteId) {
          await this.$api.notes.update(this.noteId, noteData)
        } else {
          await this.$api.notes.create(noteData)
        }
        
        uni.showToast({
          title: 'Saved successfully',
          icon: 'success'
        })
        
        uni.navigateBack()
      } catch (error) {
        uni.showToast({
          title: 'Failed to save note',
          icon: 'error'
        })
      } finally {
        uni.hideLoading()
      }
    },
    validateNote() {
      if (!this.note.title.trim()) {
        uni.showToast({
          title: 'Please enter a title',
          icon: 'none'
        })
        return false
      }
      return true
    },
    async uploadAttachments() {
      // 实现附件上传逻辑
      const uploadPromises = this.note.attachments.map(async (file) => {
        if (file.uploaded) return file
        
        try {
          const uploadResult = await this.$api.upload.file(file.path)
          return {
            ...file,
            url: uploadResult.url,
            uploaded: true
          }
        } catch (error) {
          throw new Error(`Failed to upload ${file.name}`)
        }
      })
      
      return Promise.all(uploadPromises)
    }
  }
}
</script>

<style lang="scss" scoped>
.note-edit {
  min-height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  position: relative;
}

.status-bar {
  height: var(--status-bar-height);
  width: 100%;
  background-color: #ffffff;
}

.nav-bar {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  background-color: #ffffff;
  border-bottom: 2rpx solid #f0f0f0;
  position: relative;
  z-index: 100;

  .nav-left, .nav-right {
    display: flex;
    align-items: center;
  }
}

.content-container {
  flex: 1;
  position: relative;
}

.header-section {
  padding: 30rpx;
  background-color: #ffffff;

  .title-input {
    margin-bottom: 20rpx;
  }

  .category-wrapper {
    :deep(.category-title) {
      display: flex;
      align-items: center;
      gap: 10rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
}

.editor-toolbar {
  background-color: #ffffff;
  border-top: 2rpx solid #f0f0f0;
  border-bottom: 2rpx solid #f0f0f0;
  transition: box-shadow 0.3s ease;
  position: sticky;
  top: 0;
  z-index: 99;

  &.toolbar-shadow {
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

  .toolbar-scroll {
    white-space: nowrap;
    padding: 16rpx 20rpx;
  }

  .toolbar-inner {
    display: inline-flex;
    align-items: center;
    gap: 20rpx;
  }

  .toolbar-group {
    display: flex;
    gap: 12rpx;
  }

  .toolbar-divider {
    width: 2rpx;
    height: 32rpx;
    background-color: #e0e0e0;
  }

  .toolbar-btn {
    width: 64rpx;
    height: 64rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8rpx;
    transition: all 0.2s ease;

    &:active {
      background-color: #f0f0f0;
    }

    &.active {
      background-color: #e6f7ff;
      color: #1890ff;
    }
  }
}

.editor-wrapper {
  padding: 30rpx;
  min-height: 400rpx;

  .editor {
    min-height: 400rpx;
    font-size: 28rpx;
    line-height: 1.6;
    color: #333;
  }
}

.attachments-section {
  padding: 30rpx;
  background-color: #f8f9fa;

  .section-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
    }

    .attachment-count {
      margin-left: 12rpx;
      font-size: 24rpx;
      color: #999;
      background-color: #f0f0f0;
      padding: 4rpx 12rpx;
      border-radius: 20rpx;
    }
  }

  .attachments-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }

  .attachment-card {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background-color: #ffffff;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .attachment-icon {
      margin-right: 16rpx;
    }

    .attachment-info {
      flex: 1;
      overflow: hidden;

      .attachment-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 4rpx;
        // @include text-ellipsis;
      }

      .attachment-size {
        font-size: 24rpx;
        color: #999;
      }
    }

    .attachment-action {
      padding: 10rpx;
    }
  }
}

.bottom-bar {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-top: 2rpx solid #f0f0f0;
  transition: box-shadow 0.3s ease;

  &.bar-shadow {
    box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  }

  .attachment-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    height: 80rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    color: #666;
    font-size: 28rpx;
    transition: all 0.2s ease;

    &:active {
      background-color: #e8e8e8;
    }
  }
}

// Utility classes
@mixin text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 